package com.candy.candymessage.utils;

/**
 * @author suYanLong
 * @version 1.0
 * @date 2023/5/19 16:03
 * @Description 描述
 */
public class SleepTest {

    /**
     * 虚假唤醒
     *
     * @param args
     */
    public static void main(String[] args) {
        Data data = new Data();
        //生产者线程A
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        //生产者线程B
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        //消费者线程C
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        //消费者线程D
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }

    //数据类
    static class Data {

        //表示数据个数
        private int number = 0;

        public synchronized void increment() throws InterruptedException {
            if (number != 0) {
                this.wait();
            }
            number++;
            System.out.println(Thread.currentThread().getName() + "生产了数据:" + number);
            this.notifyAll();
        }

        public synchronized void decrement() throws InterruptedException {
            if (number == 0) {
                this.wait();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "消费了数据:" + number);
            this.notifyAll();
        }

    }

}
